
// import TableList from "@components/templates/tablelist";
import TableList from "@components/templates/customtablelist";
import { HttpLabelList, HttpGetCountByStatusNum, HttpCarrierAllList, HttpCarrierServiceList,HttpUpdateTrack,HttpBatchWaybill,HttpBatchCancel,HttpBatchDel, HttpCarrierList, HttpSysCarrierServiceList, HttpGetCustomServiceProductAllList } from '@/service/api/views'
import { mapState, mapGetters } from "vuex";
import { h,resolveComponent } from 'vue'
import compUpload from '@components/templates/upload'
import compTracking from './newalert/trackingDetail';
import compTrackDetail from '../account/freeze/trackdetail';
import compIndex from './edit'
import compUploadNew from './labelupload.vue'
import mixins from './mixin'
export default {
    mixins: [TableList,mixins],
    components: {
        compUpload,
        compTracking,
        compTrackDetail,
        compIndex,
        compUploadNew
    },
    data () {
        return {
            // totals: 0,
            isMixin: true,
            Tools: { show: true },
            Tabs: { show: true },
            formData: {
                search: {
                }
            },
            Searchs: {
                show: true,
                labelWidth: 120,
            },
            Plugins: { show: true },
            spanTabs: { show: true },
            totalnum: '',
            carrierList:[],
            carrierServiceList:[],
            dayList:[
                {value:-3,label:'>3天'},
                {value:-7,label:'>7天'},
                {value:-15,label:'>15天'},
                {value:-30,label:'>30天'},
                {value:-45,label:'>45天'},
                {value:-60,label:'>60天'},
            ],
            exportData:{},
        }
    },
    created(){
        // HttpCarrierAllList()
        HttpCarrierList().then(res=>{
            this.carrierList = res.data.map(item=>{
                return {
                    value:item.carrierCode,
                    label:item.carrierCode+' ('+item.carrierName+')',
                }
            })
        })
        // HttpCarrierServiceList()
        // HttpSysCarrierServiceList()
        HttpGetCustomServiceProductAllList().then(res=>{
            console.log(res.data)
            this.carrierServiceList = res.data.map(item=>{
                return {
                    value:item.code,
                    label:item.code,
                }
            })
        })
    },
    methods: {
        ajaxRequest: HttpLabelList,
        spanAjaxRequest: HttpGetCountByStatusNum,
        interceptRequest (params) {
            if (params.search.BT_createdAt && params.search.BT_createdAt[0] != '') {
                params.search.BT_createdAt = this.handleDateFormat(params.search.BT_createdAt[0], 'yyyy-mm-dd') + ' ~ ' + this.handleDateFormat(params.search.BT_createdAt[1], 'yyyy-mm-dd')
            }
            if (params.search.BT_labelAcquiredAt && params.search.BT_labelAcquiredAt[0] != '') {
                params.search.BT_labelAcquiredAt = this.handleDateFormat(params.search.BT_labelAcquiredAt[0], 'yyyy-mm-dd') + ' ~ ' + this.handleDateFormat(params.search.BT_labelAcquiredAt[1], 'yyyy-mm-dd')
            }
            if (params.search.BT_cancelAt && params.search.BT_cancelAt[0] != '') {
                params.search.BT_cancelAt = this.handleDateFormat(params.search.BT_cancelAt[0], 'yyyy-mm-dd') + ' ~ ' + this.handleDateFormat(params.search.BT_cancelAt[1], 'yyyy-mm-dd')
            }
            if (params.search.BT_firstTrack) {
                params.search.BT_firstTrack = this.getDay(params.search.BT_firstTrack)+' 00:00:00' + '~' + this.getDay(0)+' 00:00:00'
            } else {
                params.search.BT_firstTrack = ""
            }
            if (params.search.BT_finalTrack) {
                params.search.BT_finalTrack = this.getDay(params.search.BT_finalTrack)+' 00:00:00' + '~' + this.getDay(0)+' 00:00:00'
            } else {
                params.search.BT_finalTrack = ""
            }
            if(params.search.IN_trackingStatus == 'cancelled'){
                params.search.IN_cancel = 1
                delete params.search.IN_trackingStatus
            }
            // 关联单号&关联号码
            let arr1,arr2=[],arr3,arr4=[];
            if(params.search.IN_parcelNo){
                arr1 = params.search.IN_parcelNo.split(/\n/);
                arr1.map(item=>{
                    if(item){
                        arr2.push(item)
                    }
                })
                if(arr2.length>0){
                    params.search.IN_parcelNo = arr2.toString()
                }

            }
            if(params.search.IN_trackingCode){
                arr3 = params.search.IN_trackingCode.split(/\n/);
                arr3.map(item=>{
                    if(item){
                        arr4.push(item)
                    }
                })
                if(arr4.length>0){
                    params.search.IN_trackingCode = arr4.toString()
                }
            }

            // 单据类型条件查询
            if(params.search.EQ_ordertype){
                console.log(params.search.EQ_ordertype,'params.search.EQ_ordertype')
                let arr = []
                params.search.EQ_ordertype.map(item=>{
                    if(item==0){
                        params.search.EQ_returnLabel = 1
                    }else if(item==1){
                        params.search.EQ_isThirdParty = 1
                    }else{
                        params.search.EQ_isInternational = 1
                    }
                })
            }
            delete params.search.EQ_ordertype;
            this.exportData = params;
            return params
        },
        toolsRender() { //自定义工具行
            return <div style="background: #fff;margin-bottom: 10px;padding: 5px;padding-left: 10px;">
                    <Button type="primary" onClick={this.handleOperates.bind(this,'','add')} icon="plus">添加</Button>
                    {/* <Button type="warning" class="margin-left-5" onClick={this.handleOperates.bind(this,'','upload')}>导入</Button> */}
                    <Button type="warning" class="margin-left-5" onClick={this.handleOperates.bind(this,'','uploadNew')}>导入</Button>
                    <Button type="success" class="margin-left-5" onClick={this.handleOperates.bind(this,'','searchTrack')}>查询</Button>
                    <Button type="info" class="margin-left-5" onClick={this.handleOperates.bind(this,'','searchLogistic',true)}>更新查询物流</Button>

                    <Dropdown class="margin-left-5" placement="bottom-start"
                                v-slots={{list:()=> <DropdownMenu >
                                <DropdownItem onClick={this.handleOperates.bind(this,'','download')}>导出</DropdownItem>
                                <DropdownItem onClick={this.handleOperates.bind(this,'','print',true)}>批量打印</DropdownItem>
                                <DropdownItem onClick={this.handleOperates.bind(this,'','getlabel',true)}>批量获取</DropdownItem>
                                <DropdownItem onClick={this.handleOperates.bind(this,'','getcancel',true)}>批量取消</DropdownItem>
                                <DropdownItem onClick={this.handleOperates.bind(this,'','getdelect',true)}>批量删除</DropdownItem>
                                <DropdownItem v-show="formData.EQ_cancel!=1" onClick={this.handleOperates.bind(this,'','getdownload',true)}>运单下载</DropdownItem>
                            </DropdownMenu>}}>
                        <Button>
                            更多操作&nbsp;<Icon type="ios-arrow-down"></Icon>
                        </Button>
                    </Dropdown>
                </div>

        },
        handleOperates (params = "", type, batch) {
            if (batch === true) {
                params = (params || this.checkedData.join(',')) + '';
                if (!params.length) return this.$Message.warning('请选择至少一条数据');
            }
            switch (type) {
                case 'add':
                    const url = this.$router.resolve({
                        name: 'labelAdd',
                        params: { id:params },
                        query: { type },
                    });
                    window.open(url.href, '_blank');

                    break;
                case 'edit':

                    this.operate = {
                        show:true,
                        title:'查看详情',
                        width:'1100px',
                        actived:params.id,
                        trackDetail:params.trackDetail,
                        component:'compIndex',
                        showFooter:false,
                    }
                    break;
                case 'queryBlank':
                    const url1 = this.$router.resolve({ name: 'labelDetail', params: { id:params.id }, query: { type,trackDetail:params.trackDetail } });
                    window.open(url1.href, '_blank');
                    break;
                // case 'upload':
                //     this.operate = {
                //         show: true,
                //         title: '导入数据',
                //         warningtitle: '<div style="text-align:left">包裹长、宽、高请输入正整数，若输入小数，则自动向上取整；包裹重量保留小数点后两位，超过两位则四舍五入保留两位</div>',
                //         action: process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/upload",
                //         name: "file",
                //         component: "compUpload",
                //         download: () => {
                //             this.handleWebfs(process.env.VUE_APP_APIURL_SHIP + '/api/jwt/spl/shippinginfo/downloadTemplate', { }, 'download')
                //         },
                //         showFooter:false,
                //         width:500,
                //     }
                //     break;
                case 'uploadNew':
                    this.operate = {
                        show: true,
                        title: '运单导入',
                        action: process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/upload",
                        name: "file",
                        component: "compUploadNew",
                        download: () => {
                            this.handleWebfs(process.env.VUE_APP_APIURL_SHIP + '/api/jwt/spl/shippinginfo/downloadTemplate', { }, 'download')
                        },
                        accept: '.xls, .xlsx',
                        picSrc: "/img/labelimport.png",
                        uploadRemark: `<ul><li>支持导入格式为xlsx的文件（手动修改文件后缀无效）</li><li>子母单不超过30单</li></ul>`,
                        multiple: true,
                        showFooter:false,
                        width:800,
                    }
                    break;
                case 'searchTrack':
                    // trackNo:this.checkedId
                    let trackList = [];
                    this.checkedRowData.map(item=>{
                        trackList.push(item.trackingCode)
                    })
                    let stringNo = trackList.join(',')
                    const url2 = this.$router.resolve({
                        name: 'labelSearchLogistic',
                        query:{type:'customer',trackNo:stringNo},
                    });
                    window.open(url2.href, '_blank');
                    break;
                case 'searchLogistic':
                    this.operate = {
                        show: true,
                        alert: "warning",
                        params: { ids: params },
                        title: "更新查询操作",
                        ajaxRequest: HttpUpdateTrack
                    }
                    break;
                case 'download':
                    this.handleWebfs(
                        process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/export", {...this.exportData},
                        "download"
                    );
                    break;
                case 'print':
                    this.operate = {
                        show: true,
                        alert: "primary",
                        params: { id: params,status:1 },
                        title: "确认操作",
                        ajaxRequest: async () => {
                            this.$Message.loading({ content: '正在处理中……', duration: 0 });
                            this.handleWebfs(process.env.VUE_APP_APIURL_SHIP + '/api/jwt/spl/shippinginfo/batchPrint', { ids: params }, {
                                executor: 'request',
                                print: true,
                                fileType: "application/pdf"
                            }).then(res=>{
                                this.$Message.destroy();
                                this.operate = {};
                            }).catch(err => {
                                this.$Message.destroy();
                                this.$Message.error({
                                    content: err.message,
                                    duration: 30,
                                    closable: true
                                });
                            });
                        }
                    }
                    break;

                case 'getlabel':
                    this.operate = {
                        show: true,
                        alert: "primary",
                        params: { ids: params, },
                        title: "获取操作",
                        ajaxRequest: HttpBatchWaybill
                    }
                    break;
                case 'getcancel':
                    this.operate = {
                        show: true,
                        alert: "warning",
                        params: { ids: params, },
                        title: "取消操作",
                        ajaxRequest: HttpBatchCancel
                    }
                    break;
                case 'getdelect':
                    this.operate = {
                        show: true,
                        alert: "warning",
                        params: { ids: params, },
                        title: "删除操作",
                        ajaxRequest: HttpBatchDel
                    }
                    break;
                case 'getdownload':
                    this.handleWebfs(
                        process.env.VUE_APP_APIURL_SHIP + "/api/jwt/spl/shippinginfo/batchLableDownLoad", {ids:params},
                        "download"
                    );
                    break;
                case 'seeTracking':
                    if(!params){this.$Message.error('没有运单详情数据！');return;}
                    this.operate = {
                        show: true,
                        title:'查看运单详情',
                        component: "compTracking",
                        trackDetail:params,//(实际传参是trackDetail)
                        showFooter:false
                    }
                    break;
                case 'queryTrack':
                    this.operate = {
                        show:true,
                        title:'查看详情',
                        width:'1000px',
                        trackingNo:params,
                        component:'compTrackDetail',
                        showFooter:false,
                    }
                    break;
            }
        },
    },
    computed: {
        ...mapGetters('dictionary', ['getSysAllList']),
        TabsData () {
            return [
                {
                    name: this.$ct('global.common.all', { defaultValue: '全部' }),
                    key: 'IN_trackingStatus',
                    val: null,
                }, {
                    name: '初始化',
                    key: 'IN_trackingStatus',
                    val: "unknown",
                }, {
                    name: '待发运',
                    key: 'IN_trackingStatus',
                    val: "pre_transit",
                }, {
                    name: '在途',
                    key: 'IN_trackingStatus',
                    val: "in_transit",
                }, {
                    name: '派送中',
                    key: 'IN_trackingStatus',
                    val: "out_for_delivery,available_for_pickup",
                }, {
                    name: '已妥投',
                    key: 'IN_trackingStatus',
                    val: "delivered",
                }, {
                    name: '异常',
                    key: 'IN_trackingStatus',
                    val: "failure,error",
                    spanKey: 'error',
                }, {
                    name: '已取消',
                    key: 'IN_trackingStatus',
                    val: "cancelled",
                }, {
                    name: '已退回',
                    key: 'IN_trackingStatus',
                    val: "return_to_sender",
                }
            ]
        },
        // 搜索下拉框展示内容
        SearchsData () {
            return [
                {
                    label: '承运商',
                    tag: 'Select',
                    key: 'EQ_carrier',
                    options:this.carrierList,
                    show:true,
                    props:{
                        filterable:true
                    }
                },
                {
                    label: '关联单号',
                    tag: 'Input',
                    key: 'IN_parcelNo',
                    props: {
                        type:'textarea',
                        rows:"1"
                    },
                    show: true,
                    style:'width:200px'
                },
                {
                    label: '运单号码',
                    tag: 'Input',
                    key: 'IN_trackingCode',
                    props: {
                        type:'textarea',
                        rows:"1"
                    },
                    show: true,
                    style:'width:200px'
                },

                {
                    label: '发货地址code',
                    tag: 'Input',
                    key: 'EQ_shipperCode',
                },
                {
                    label: '单据状态',
                    tag: 'Select',
                    key: 'EQ_status',
                    options:[
                        {value:0,label:'已创建'},
                        {value:1,label:'已获取'},
                        {value:2,label:'已打印'},
                        {value:4,label:'已扣款'},
                        {value:5,label:'已计费'},
                    ],
                },
                {
                    label: '上网至今',
                    tag: 'Select',
                    key: 'BT_firstTrack',
                    options:this.dayList,
                },
                {
                    label: '最后事件至今',
                    tag: 'Select',
                    key: 'BT_finalTrack',
                    options:this.dayList,
                },
                {
                    label: '承运商服务',
                    tag: 'Select',
                    key: 'EQ_logisticsServiceCode',
                    options:this.carrierServiceList,
                    props:{
                        filterable:true,
                    }
                },
                {
                    label: '是否取消',
                    tag: 'Select',
                    key: 'EQ_cancel',
                    options:[
                        {value:1,label:'已取消'},
                        {value:0,label:'未取消'},
                    ],
                },
                {
                    label: '单据类型',
                    tag: 'Select',
                    key: 'EQ_ordertype',
                    options:[
                        {value:0,label:'退货单'},
                        {value:1,label:'3rd party'},
                        {value:2,label:'国际单'},
                    ],
                    props:{
                        multiple:true,
                    }
                },
                {
                    label: '创建时间',
                    tag: 'DatePicker',
                    key: 'BT_createdAt',
                    props: {
                        options:this.options,
                        type: 'daterange',
                    },
                    // hideSearchTip: true,
                },
                {
                    label: '运单获取时间',
                    tag: 'DatePicker',
                    key: 'BT_labelAcquiredAt',
                    props: {
                        options:this.options,
                        type: 'daterange',
                    },
                    // hideSearchTip: true,
                },
                {
                    label: '取消时间',
                    tag: 'DatePicker',
                    key: 'BT_cancelAt',
                    props: {
                        options:this.options,
                        type: 'daterange',
                    },
                    // hideSearchTip: true,
                },
            ]
        },
        // table的展示数据
        columns () {
            return [{
                title: "复选框",
                width: 60,
                align: "center",
                type: 'selection',
            },
            // {
            //     title: "ID",
            //     key: "id",
            //     align: "center",
            //     sortable: true,
            //     width: 90,
            //     render: (h, { row }) => {
            //         return <a onClick={this.handleOperates.bind(this, row.id, 'edit')}>{row.id}</a>
            //     }
            // },
            {
                title: "单据状态",
                key: "status",
                align: "center",
                width: 90,
                render (h, { row }) {
                    let type = null;
                    switch (row.status) {
                        case 0: type = "已创建"; break;
                        case 1: type = "已获取"; break;
                        case 2: type = "已打印"; break;
                        case 4: type = "已扣款"; break;
                        case 5: type = "已计费"; break;
                        default: type = "已创建"; break;
                    }
                    return h('span', type);
                }
            },
            {
                title:'客户组织',
                key: "organizationId",
                align: "center",
                width: 90,
                render: (h, { row }) => {
                    return (this.getSysAllList.find(item => item.value == row.organizationId) || {}).label || ""
                },
            },
            {
                title: "运单号",
                key: "trackingCode",
                align: "center",
                sortable: true,
                minWidth: 150,
                render: (h, { row }) => {
                    return <div>
                        <a onClick={this.handleOperates.bind(this, {id:row.id,trackDetail:row.trackDetail}, 'edit')}>{row.trackingCode || '--'}</a>
                        <a onClick={this.handleOperates.bind(this, {id:row.id,trackDetail:row.trackDetail}, 'queryBlank')}><Icon class="margin-left-5 font-14" type="ios-browsers-outline" /></a>
                        <div>
                            <span v-show={row.isInternational == 1} title="国际单">
                                <Tooltip content="国际单">
                                    <span style="color:red;font-size:16px" class="iconfont icon-guojidingdan"></span>
                                </Tooltip>
                            </span>
                            <span v-show={row.isThirdParty == 1} title="3rd Party" style="text-align:center;padding:0 5px ">
                                <Tooltip content="3rd Party">
                                    <span style="color:#1296db;font-size:16px;" class="iconfont icon-disanfangdanbao"></span>
                                </Tooltip>
                            </span>
                            <span v-show={row.returnLabel == 1} title="退货单" style="text-align:center;padding:0 5px;display:inline-block ">
                                <Tooltip content="退货单">
                                    {/* <img src="/img/isreturn.png" style="vertical-align: top;width:16px" /> */}
                                    <span style="font-size:16px" class="iconfont icon-tui"></span>
                                </Tooltip>
                            </span>
                        </div>
                    </div>
                }
            }, {
                title: "关联单号",
                key: "parcelNo",
                align: "center",
                sortable: true,
                minWidth: 100,
                render (h, { row }) {
                    return <div>
                        <div>{row.parcelNo || '--'}</div>
                    </div>
                }
            },
            {
                title: "预估费用(USD)",
                key: "rate",
                align: "center",
                sortable: true,
                minWidth: 140,
                render: (h, { row })=>{
                    return <div>
                        <a onClick={this.handleOperates.bind(this, row.trackingCode, 'queryTrack')}>{row.rate || '--'}</a>
                    </div>
                }
            }, {
                title: "承运商/服务",
                key: "carrier",
                align: "center",
                minWidth: 110,
                render (h, { row }) {
                    return <div>
                        <div>{row.carrier || '--'}</div>
                        <div>{row.logisticsServiceCode || '--'}</div>
                    </div>
                }
            },
            {
                title: "物流最新状态",
                key: "trackingStatus",
                align: "center",
                minWidth: 100,
                render (h, { row }) {
                    let type = null;
                    switch (row.trackingStatus) {
                        case 'unknown': type = "初始化"; break;
                        case 'pre_transit': type = "待发运"; break;
                        case 'in_transit': type = "在途"; break;
                        case 'out_for_delivery': type = "派送中"; break;
                        case 'available_for_pickup': type = "派送中"; break;
                        case 'delivered': type = "已妥投"; break;
                        case 'return_to_sender': type = "已退回"; break;
                        case 'cancelled': type = "已取消"; break;
                        case 'failure': type = "异常"; break;
                        case 'error': type = "异常"; break;
                    }
                    return h('span', type);
                }
            },
            {
                title: "是否取消",
                key: "status",
                align: "center",
                minWidth: 70,
                render (h, { row }) {
                    return <div>
                        <div>{row.cancel == 0 ? '否' : '是'}</div>
                    </div>
                }
            },
            {
                title: "物流最新事件",
                minWidth: 150,
                align: "center",
                render: (h, { row }) => {
                    let arr = [{
                        city: '--',
                        state: '--',
                        country: '--',
                        message: '--'
                    }]
                    if (!!row.trackDetail) {
                        arr = JSON.parse(row.trackDetail)
                    }
                    return <div>
                        <div v-show={!!row.trackDetail}>{arr[0].city},{arr[0].state},{arr[0].country},{arr[0].status},{arr[0].statusDetail}</div>
                        <span v-show={!!row.trackDetail}>
                            <Tooltip content="上网至今天数"><span style="padding:2px 10px;background:#19be6b;color:#fff;border-radius: 10px;">{!!row.firstTrack ? this.getDifferDate(row.firstTrack.split(' ')[0], this.getNowDate(), 1) : '--'}</span></Tooltip>
                        </span>
                        <span v-show={!!row.trackDetail}>
                            <Tooltip content="最后事件至今天数"><span style="padding:2px 10px;background:#f90;color:#fff;margin-left:5px;border-radius: 10px;">{!!row.finalTrack ? this.getDifferDate(row.finalTrack.split(' ')[0], this.getNowDate(), 1) : '--'}</span></Tooltip>
                        </span>
                        <div v-show={!row.trackDetail}>--</div>
                    </div>
                }
            },
            {
                title: "运单购买来源",
                minWidth: 110,
                align: "center",
                render (h, { row }) {
                    let type = null;
                    switch (row.systemSource) {
                        case 0: type = "页面购买"; break;
                        case 1: type = "API"; break;
                    }
                    return h('span', type);
                }
            }, {
                title: "创建/运单获取/取消",
                minWidth: 220,
                align: "center",
                sortable: true,
                render: (h, { row }) => {
                    return <div>
                        <div>{row.createdAt || '--'}</div>
                        <div>{row.labelAcquiredAt || '--'}</div>
                        <div>{row.cancelAt || '--'}</div>
                    </div>
                }
            }
            ];
        },

    },

};
